package com.daocao.hua.activity;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.CardView;
import android.text.Html;
import android.text.Spanned;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.daocao.hua.R;
import com.daocao.hua.api.bean.UploadSubmitIdcardBean;
import com.daocao.hua.api.callback.IdcardV2Contract;
import com.daocao.hua.api.requestInfo.IdcardV2Request;
import com.daocao.hua.constant.Const;
import com.daocao.hua.constant.IdCardBitmap;
import com.daocao.hua.constant.UserGlobal;
import com.daocao.hua.event.OnEndIdentityMsg;
import com.daocao.hua.event.SelectParentEvent;
import com.daocao.hua.model.AddressModel;
import com.daocao.hua.model.BankListModel;
import com.daocao.hua.model.DealBeforeModel;
import com.daocao.hua.model.IdentityModel;
import com.daocao.hua.model.RelativeListModel;
import com.daocao.hua.model.ResponseModel;
import com.daocao.hua.util.DisplayUtil;
import com.daocao.hua.util.ImageUtil;
import com.daocao.hua.util.PreferenceUtils;
import com.daocao.hua.util.ScacheUtil;
import com.daocao.hua.util.StatusBarCompat;
import com.daocao.hua.util.ToastUtil;
import com.daocao.hua.util.UI;
import com.daocao.hua.util.Util;
import com.daocao.hua.view.AutoSetHeightRoundImageView;
import com.daocao.hua.view.BankViewItem;
import com.daocao.hua.view.CircularProgress;
import com.daocao.hua.view.Dialog;
import com.daocao.hua.view.LastInputEditText;
import com.daocao.hua.view.ObservableScrollView;
import com.daocao.hua.view.animation.YoYo;
import com.lljjcoder.citypickerview.widget.CityPicker;
import com.readystatesoftware.systembartint.SystemBarTintManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import chihane.jdaddressselector.BottomDialog;
import chihane.jdaddressselector.OnAddressSelectedListener;
import chihane.jdaddressselector.model.City;
import chihane.jdaddressselector.model.County;
import chihane.jdaddressselector.model.Province;
import chihane.jdaddressselector.model.Street;

/**
 * Created by xsooy-pc on 2017/7/20.
 */
public class Idcardv2Activity extends BaseActivity implements ObservableScrollView.ScrollViewListener, IdcardV2Contract.View, OnAddressSelectedListener {


    @BindView(R.id.layout_take_photo)
    LinearLayout layoutTakePhoto;
    @BindView(R.id.layout_identity_total)
    FrameLayout layoutIdentityTotal;
    @BindView(R.id.scrollView)
    ObservableScrollView scrollView;
    @BindView(R.id.toolbar)
    FrameLayout toolbar;
    @BindView(R.id.layout_idcard_top)
    LinearLayout layoutIdcardTop;
    @BindView(R.id.progressBar)
    CircularProgress loading;
    @BindView(R.id.front_iv)
    AutoSetHeightRoundImageView frontIv;
    @BindView(R.id.take1)
    ImageView take1;
    @BindView(R.id.back_iv)
    AutoSetHeightRoundImageView backIv;
    @BindView(R.id.take2)
    ImageView take2;
    @BindView(R.id.txt_name)
    LastInputEditText txtName;
    @BindView(R.id.txt_idno)
    TextView txtIdno;
    @BindView(R.id.txt_front_tips)
    TextView txtFrontTips;
    @BindView(R.id.layout_front)
    RelativeLayout layoutFront;
    @BindView(R.id.txt_address)
    LastInputEditText txtAddress;
    @BindView(R.id.txt_time)
    TextView txtTime;
    @BindView(R.id.layout_back)
    RelativeLayout layoutBack;
    @BindView(R.id.layout_chsi_toal)
    LinearLayout layoutChsiToal;
    @BindView(R.id.layout_bank_total)
    LinearLayout layoutBankTotal;
    @BindView(R.id.code_iv)
    ImageView codeIv;
    @BindView(R.id.code_view)
    LinearLayout codeView;
    @BindView(R.id.cb_check)
    CheckBox cbCheck;
    @BindView(R.id.txt_agree)
    TextView txtAgree;
    @BindView(R.id.txt_username)
    EditText txtUsername;
    @BindView(R.id.txt_password)
    EditText txtPassword;
    @BindView(R.id.code)
    EditText code;
    @BindView(R.id.icon)
    ImageView icon;
    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.cardno)
    TextView cardno;
    @BindView(R.id.bank_view)
    CardView bankView;
    @BindView(R.id.left_img_first)
    ImageButton leftImgFirst;
    @BindView(R.id.txt_relative_one_content)
    TextView txtRelativeOneContent;
    @BindView(R.id.txt_relative_two_content)
    LastInputEditText txtRelativeTwoContent;
    @BindView(R.id.txt_relative_three_content)
    LastInputEditText txtRelativeThreeContent;
    @BindView(R.id.txt_id_title)
    TextView txtIdTitle;
    @BindView(R.id.txt_id_tips)
    TextView txtIdTips;
    @BindView(R.id.btn_submit)
    TextView btnSubmit;
    @BindView(R.id.edit_long_address)
    EditText editLongAddress;
    @BindView(R.id.layout_bank_first)
    RelativeLayout layoutBankFirst;
    @BindView(R.id.layout_bank_sec)
    LinearLayout layoutBankSec;
    @BindView(R.id.img_banner)
    ImageView imgBanner;
    @BindView(R.id.view_line)
    View viewLine;
    @BindView(R.id.btn_edit_front)
    TextView btnEditFront;
    @BindView(R.id.txt_back_tips)
    TextView txtBackTips;
    @BindView(R.id.btn_edit_back)
    TextView btnEditBack;
    @BindView(R.id.layout_identity)
    LinearLayout layoutIdentity;
    @BindView(R.id.layout_xuexin_user)
    LinearLayout layoutXuexinUser;
    @BindView(R.id.layout_xuexin_pass)
    LinearLayout layoutXuexinPass;
    @BindView(R.id.txt_forget)
    TextView txtForget;
    @BindView(R.id.rl_default_bank_icon)
    RelativeLayout rlDefaultBankIcon;
    @BindView(R.id.pic2)
    RelativeLayout pic2;
    @BindView(R.id.txt_bank_one)
    TextView txtBankOne;
    @BindView(R.id.btn_bank_tongxun)
    TextView btnBankTongxun;
    @BindView(R.id.txt_relative_one)
    TextView txtRelativeOne;
    @BindView(R.id.rl_relative_select)
    RelativeLayout rlRelativeSelect;
    @BindView(R.id.view_relative_one)
    View viewRelativeOne;
    @BindView(R.id.txt_relative_two)
    TextView txtRelativeTwo;
    @BindView(R.id.txt_relative_three)
    TextView txtRelativeThree;
    @BindView(R.id.layout_total_take_photo)
    LinearLayout layoutTotalTakePhoto;
    @BindView(R.id.imageView2)
    ImageView imageView2;
    @BindView(R.id.left_img)
    ImageButton leftImg;
    @BindView(R.id.ll_relative_two)
    LinearLayout llRelativeTwo;
    @BindView(R.id.ll_relative_three)
    LinearLayout llRelativeThree;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.view_total_bg)
    ImageView viewTotalBg;
    @BindView(R.id.fl_bank_view)
    FrameLayout flBankView;
    @BindView(R.id.layout_address_two)
    RelativeLayout layoutAddressTwo;
    @BindView(R.id.txt_area_content)
    EditText txtAreaContent;
    @BindView(R.id.rl_area)
    RelativeLayout rlArea;
    @BindView(R.id.layout_total_address)
    LinearLayout layoutTotalAddress;
    private float headerHeight;//顶部高度
    private float minHeaderHeight;//顶部最低高度，即Bar的高度
    private int btnId;
    private Unbinder unbinder;
    private boolean isFirst = true;
    private IdcardV2Request api;
    private UploadSubmitIdcardBean newModel = new UploadSubmitIdcardBean();
    private int poi = 0;
    private YoYo.YoYoString rope;
    private boolean frontIdentity = false;
    private boolean backIdentity = false;
    private String realName;
    private BankViewItem bankViewItem;
    private boolean bankIdentity = false;
    private InputMethodManager imm;
    private DealBeforeModel totalData;
    private boolean isLast;
    private boolean isRelativeIdentity = false;
    private BottomDialog bottomDialog;
    private String province;
    private String city;
    private String area;
    private float floatTitleSize;
    private float floatTitleSizeLarge;
    private float titleScale;
    private boolean isNeedCode = false;

    @OnClick({R.id.rl_area, R.id.txt_relative_one_content, R.id.ll_relative_three, R.id.ll_relative_two, R.id.left_img_first, R.id.layout_bank_first, R.id.btn_bank_tongxun, R.id.rl_relative_select, R.id.bank_view, R.id.code_iv, R.id.btn_submit, R.id.take1, R.id.take2, R.id.left_img, R.id.btn_edit_front, R.id.btn_edit_back, R.id.front_iv, R.id.back_iv, R.id.txt_forget, R.id.txt_agree})
    public void onViewClicked(View view) {
        if (UI.isFastClick()) {
            return;
        }
        switch (view.getId()) {

            case R.id.left_img_first:
                if (poi == 1) {
                    Util.startActivity(Idcardv2Activity.this, ChsiQuestionActivity.class);
                    return;
                }
                showDialog();
                break;
            case R.id.left_img:
                if (poi == 1) {
                    Util.startActivity(Idcardv2Activity.this, ChsiQuestionActivity.class);
                    return;
                }
                showDialog();
                break;
            case R.id.btn_submit:
//                身份证页面判断
                if (poi == 0) {
                    if (!frontIdentity) {
                        ToastUtil.makeText(this, "请上传身份证正面").show();
                        return;
                    }
                    if (!backIdentity) {
                        ToastUtil.makeText(this, "请上传身份证反面").show();
                        return;
                    }
                    newModel.setName(UI.toString(txtName));
                    newModel.setIssue_by(UI.toString(txtAddress));
                    api.getSubmitidCard(newModel);
                } else if (poi == 1) {
                    if (TextUtils.isEmpty(UI.toString(txtUsername))) {
                        ToastUtil.makeText(this, "请输入学信网账号").show();
                        return;
                    }
                    if (TextUtils.isEmpty(UI.toString(txtPassword))) {
                        ToastUtil.makeText(this, "请输入学信网密码").show();
                        return;
                    }
                    //                学信网页面判断
//                    if (codeView.getVisibility() == View.GONE) {
//                        api.getChsiCode(UI.toString(txtUsername), UI.toString(txtPassword));
//                    } else {
                    api.getChsiLogin(UI.toString(txtUsername), UI.toString(txtPassword), UI.toString(code));
//                    }
                } else if (poi == 2) {
//                    银行卡页面判断
                    if (!bankIdentity) {
                        ToastUtil.makeText(this, "请绑定银行卡").show();
                        return;
                    }

                    if (TextUtils.isEmpty(UI.toString(txtAreaContent))) {
                        ToastUtil.makeText(this, "请填写区域").show();
                        return;
                    }
                    if (TextUtils.isEmpty(UI.toString(editLongAddress))) {
                        ToastUtil.makeText(this, "请填写地址").show();
                        return;
                    }
                    if (!isRelativeIdentity) {
                        if (TextUtils.isEmpty(UI.toString(txtRelativeOneContent))) {
                            ToastUtil.makeText(this, "请选择联系人关系").show();
                            return;
                        }
                        if (TextUtils.isEmpty(UI.toString(txtRelativeTwoContent))) {
                            ToastUtil.makeText(this, "请填写联系人姓名").show();
                            return;
                        }
                        if (TextUtils.isEmpty(UI.toString(txtRelativeThreeContent))) {
                            ToastUtil.makeText(this, "请填写联系人号码").show();
                            return;
                        }
                        if (UI.toString(txtRelativeThreeContent).length() != 11) {
                            ToastUtil.makeText(this, "请填写11位正确手机号码").show();
                            return;
                        }
                    }
                    if (!TextUtils.isEmpty(newModel.getName())) {
                        api.updateAddress(newModel.getName(), UI.toString(editLongAddress), PreferenceUtils.getString(this, "mobile", ""), province, city, area);
                    } else if (!TextUtils.isEmpty(PreferenceUtils.getString(this, "real_name", ""))) {
                        api.updateAddress(PreferenceUtils.getString(this, "real_name", ""), UI.toString(editLongAddress), PreferenceUtils.getString(this, "mobile", ""), province, city, area);
                    } else if (!TextUtils.isEmpty(PreferenceUtils.getString(this, "username", ""))) {
                        api.updateAddress(PreferenceUtils.getString(this, "username", ""), UI.toString(editLongAddress), PreferenceUtils.getString(this, "mobile", ""), province, city, area);
                    }
                }
                break;
            case R.id.take1:
                checkCameraPermission(1);
                break;
            case R.id.front_iv:
                checkCameraPermission(1);
                break;
            case R.id.take2:
                checkCameraPermission(2);
                break;
            case R.id.back_iv:
                checkCameraPermission(2);
                break;
            case R.id.ll_relative_three:
                txtRelativeThreeContent.setFocusable(true);
                txtRelativeThreeContent.setFocusableInTouchMode(true);
                txtRelativeThreeContent.requestFocus();
                //打开软键盘
                imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                break;
            case R.id.ll_relative_two:
                txtRelativeTwoContent.setFocusable(true);
                txtRelativeTwoContent.setFocusableInTouchMode(true);
                txtRelativeTwoContent.requestFocus();
                //打开软键盘
                imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                break;
            case R.id.btn_edit_front:
                txtName.setFocusable(true);
                txtName.setFocusableInTouchMode(true);
                txtName.requestFocus();
                //打开软键盘
                imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                break;
            case R.id.btn_edit_back:
                txtAddress.setFocusable(true);
                txtAddress.setFocusableInTouchMode(true);
                txtAddress.requestFocus();
                //打开软键盘
                imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                break;
            case R.id.txt_forget:
                Util.startActivity(this, ChsiForgetPwdV2Activity.class);
                break;
            case R.id.txt_agree:
                Intent intent = new Intent(this, AboutActivity.class);
                intent.putExtra("id", Const.ContractType.CHSI);
                intent.putExtra("type", 1);
                intent.putExtra("title", getResources().getString(R.string.service_contract_text2));
                startActivity(intent);
                this.overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                break;
            case R.id.code_iv:
                if (checkUsername() && checkPassword())
                    api.getChsiCode(UI.toString(txtUsername), UI.toString(txtPassword));
                break;

            case R.id.bank_view:
                if (TextUtils.isEmpty(realName)) {
                    api.getBankList();
                    return;
                }
                Intent bankIntent = new Intent(this, V3BankEditActivity.class);
                bankIntent.putExtra("realName", realName);
                startActivity(bankIntent);
                overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                break;
            case R.id.rl_relative_select:
                Intent selectParentIntent = new Intent(this, SelectParentsActivity.class);
                startActivityForResult(selectParentIntent, 301);
                break;
            case R.id.txt_relative_one_content:
                Intent selectParentIntent1 = new Intent(this, SelectParentsActivity.class);
                startActivityForResult(selectParentIntent1, 301);
                break;
            case R.id.btn_bank_tongxun:
                Uri uri = Uri.parse("content://contacts/people");
                Intent contactIntent = new Intent(Intent.ACTION_PICK, uri);
                checkContactPermission(contactIntent, 300);
                break;
            case R.id.layout_bank_first:
                api.getRelativeList();
                layoutBankFirst.setVisibility(View.GONE);
                layoutBankSec.setVisibility(View.VISIBLE);
                layoutTotalAddress.setVisibility(View.VISIBLE);
                layoutAddressTwo.setVisibility(View.VISIBLE);
                measureView(2);
                api.setGradientGreyTotal(true, layoutBankSec);
                break;
            case R.id.rl_area:
                bottomDialog.show();
                break;
        }
    }

    @TargetApi(Build.VERSION_CODES.M)
    private void checkContactPermission(final Intent intent, final int result) {
        checkPermission(new CheckPermListener() {
            @Override
            public void superPermission() {
                startActivityForResult(intent, result);
            }

            @Override
            public void superReject() {

            }

        }, R.string.contact_p, R.string.get_contact, Manifest.permission.WRITE_CONTACTS, Manifest.permission.READ_CONTACTS);
    }

    private void showDialog() {

        String content = null;
        String right = "";
        if (poi == 0) {
            content = totalData.data.idcard.alert;
            right = "继续认证";
        } else if (poi == 1) {
            content = totalData.data.xuexin.alert;
            right = "继续认证";
        } else if (poi == 2) {
            content = totalData.data.bankcard.alert;
            right = "继续填写";
        }
        Dialog.showDefaultRedBlackDialog(this, "提示", content, "放弃", right, true, new Dialog.DialogDefaultClickListener() {
            @Override
            public void confirm() {

            }

            @Override
            public void cancel() {
                finish();
            }
        });
    }

    public boolean checkUsername() {
        if (TextUtils.isEmpty(UI.toString(txtUsername))) {
            ToastUtil.makeText(this, "学信网账号不能为空").show();
            return false;
        }
        return true;
    }

    public boolean checkPassword() {
        if (TextUtils.isEmpty(UI.toString(txtPassword))) {
            ToastUtil.makeText(this, "学信网密码不能为空").show();
            return false;
        }
        return true;
    }

    @Override
    public void onBackPressed() {
        if (poi == 1) {
            Util.startActivity(Idcardv2Activity.this, ChsiQuestionActivity.class);
            return;
        }
        showDialog();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_v2_idcard);
        unbinder = ButterKnife.bind(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //透明导航栏
//            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            SystemBarTintManager tintManager = new SystemBarTintManager(this);
            tintManager.setStatusBarTintColor(Color.TRANSPARENT);
            tintManager.setNavigationBarTintColor(Color.parseColor("#000000"));
            tintManager.setStatusBarTintEnabled(true);
            tintManager.setNavigationBarTintEnabled(true);
        }
        init();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!bankIdentity && poi == 2) {
            api.getBankList();
        }

    }

    private void setAnimationOne(View target) {
        api.setAnimationOne(target);
    }

    private void setAnimationTwo(View target) {
        scrollView.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (poi == 0) {
                    if (totalData.data.xuexin.is_auth.equals("0") || totalData.data.xuexin.is_auth.equals("2")) {
                        txtIdTitle.setText(totalData.data.xuexin.title);
                        toolbarTitle.setText(totalData.data.xuexin.title);
                        txtIdTips.setText(totalData.data.xuexin.desc);
                        layoutChsiToal.setVisibility(View.VISIBLE);
                        measureView(1);
                        api.setGradientTotal(layoutChsiToal);
                        StringBuilder sb = new StringBuilder();
                        sb.append("我已同意并阅读");
                        sb.append("<font color='#e3483d'>");
                        sb.append(getResources().getString(R.string.service_clause));
                        sb.append("</font>");
                        Spanned spanned = Html.fromHtml(sb.toString());
                        txtAgree.setText(spanned);
                        if (totalData.data.bankcard.is_auth.equals("1")) {
                            btnSubmit.setText("获取额度");
                            isLast = true;
                        }
                    } else if (totalData.data.bankcard.is_auth.equals("0") || totalData.data.bankcard.is_auth.equals("2")) {
                        txtIdTitle.setText(totalData.data.bankcard.title);
                        toolbarTitle.setText(totalData.data.bankcard.title);
                        txtIdTips.setText(totalData.data.bankcard.desc);
                        api.setGradientGreyTotal(true, layoutBankFirst);
                        layoutBankTotal.setVisibility(View.VISIBLE);
                        measureView(2);
                        api.getBankList();
                        btnSubmit.setText("获取额度");
                        isLast = true;
                    }
                } else if (poi == 1) {
                    if (totalData.data.bankcard.is_auth.equals("0") || totalData.data.bankcard.is_auth.equals("2")) {
                        txtIdTitle.setText(totalData.data.bankcard.title);
                        toolbarTitle.setText(totalData.data.bankcard.title);
                        txtIdTips.setText(totalData.data.bankcard.desc);
                        layoutBankTotal.setVisibility(View.VISIBLE);
                        api.setGradientGreyTotal(true, layoutBankFirst);
                        measureView(2);
                        api.getBankList();
                        btnSubmit.setText("获取额度");
                        isLast = true;
                    }
                } else if (poi == 2) {

                }
            }
        }, 500);
        api.setAnimationTwo(target);
    }


    private void measureView(int type) {
    }


    private void init() {
        floatTitleSize = getResources().getDimension(R.dimen.dp_16);
        floatTitleSizeLarge = getResources().getDimension(R.dimen.dp_35);
        titleScale = floatTitleSize / floatTitleSizeLarge;
        if (!EventBus.getDefault().isRegistered(this)) {
            //注册订阅者
            EventBus.getDefault().register(this);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            leftImgFirst.post(new Runnable() {
                @Override
                public void run() {
                    int height = StatusBarCompat.getStatusBarHeight(Idcardv2Activity.this);
                    if (height == 0) {
                        return;
                    }
                    if (toolbar != null) {
                        toolbar.setPadding(0, height, 0, 0);
                    }

                    int left = DisplayUtil.dip2px(Idcardv2Activity.this, 10);
                    if (leftImgFirst != null) {
                        leftImgFirst.setPadding(0, height + left, 0, left);
                    }
                }
            });
        }
        imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        initMeasure();
        totalData = getIntent().getParcelableExtra(Const.KEY.DEAL_BEFORE);

        scrollView.setScrollViewListener(this);
        api = IdcardV2Request.create();
        api.attachView(this);
        if (totalData.data.idcard.is_auth.equals("0") || totalData.data.idcard.is_auth.equals("2")) {
            layoutTakePhoto.setVisibility(View.VISIBLE);
            measureView(0);
            poi = 0;
            if (totalData.data.bankcard.is_auth.equals("1") && totalData.data.xuexin.is_auth.equals("1")) {
                btnSubmit.setText("获取额度");
                isLast = true;
            }
        } else if (totalData.data.xuexin.is_auth.equals("0") || totalData.data.xuexin.is_auth.equals("2")) {
            layoutChsiToal.setVisibility(View.VISIBLE);
            txtIdTitle.setText(totalData.data.xuexin.title);
            toolbarTitle.setText(totalData.data.xuexin.title);
            txtIdTips.setText(totalData.data.xuexin.desc);
            measureView(1);
            api.setGradientTotal(layoutChsiToal);
            StringBuilder sb = new StringBuilder();
            sb.append("我已同意并阅读");
            sb.append("<font color='#e3483d'>");
            sb.append(getResources().getString(R.string.service_clause));
            sb.append("</font>");
            Spanned spanned = Html.fromHtml(sb.toString());
            txtAgree.setText(spanned);
            poi = 1;
            if (totalData.data.bankcard.is_auth.equals("1")) {
                btnSubmit.setText("获取额度");
                isLast = true;
            }
        } else if (totalData.data.bankcard.is_auth.equals("0") || totalData.data.bankcard.is_auth.equals("2")) {
            layoutBankTotal.setVisibility(View.VISIBLE);
            measureView(2);
            txtIdTitle.setText(totalData.data.bankcard.title);
            toolbarTitle.setText(totalData.data.bankcard.title);
            txtIdTips.setText(totalData.data.bankcard.desc);
            api.setGradientGreyTotal(true, layoutBankFirst);
            poi = 2;
            btnSubmit.setText("获取额度");
            isLast = true;

        }
        bottomDialog = new BottomDialog(this);
        bottomDialog.setOnAddressSelectedListener(this);
    }

    private void initMeasure() {
        headerHeight = getResources().getDimension(R.dimen.dp_300);
        minHeaderHeight = getResources().getDimension(R.dimen.abc_action_bar_default_height_material);

    }


    /**
     * 事件监听
     *
     * @param msg
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void ChsiRegisterEventBus(OnEndIdentityMsg msg) {
        finish();
    }


    /**
     * 事件监听
     *
     * @param msg
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void SelectParent(SelectParentEvent msg) {
        String parent = "";
        switch (msg.poi) {
            case 0:
                parent = "父亲";
                break;
            case 1:
                parent = "母亲";
                break;
            case 2:
                parent = "其他亲戚";
                break;
        }
        txtRelativeOneContent.setText(parent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (bottomDialog != null) {
            bottomDialog.dismiss();
            bottomDialog = null;
        }
        ScacheUtil.clearTextLineCache();
        api.detachView();
        api = null;
        unbinder.unbind();
    }


    @Override
    public void onScrollChanged(ObservableScrollView scrollView, int x, int y, int oldx, int oldy) {
        //Y轴偏移量
        float scrollY = scrollView.getScrollY();
//        e3483d
        //变化率
        float headerBarOffsetY = headerHeight - minHeaderHeight;//Toolbar与header高度的差值
        float offset = 1 - Math.max((headerBarOffsetY - scrollY) / headerBarOffsetY, 0f);
//        Log.i("dsadasasdsdadsa", "titlescale=" + titleScale + "scale=" + (1 - offset * (1 - titleScale)));
        //标题文字X轴缩放
        txtIdTitle.setScaleX(1 - offset * (1 - titleScale));
        //标题文字Y轴缩放
        txtIdTitle.setScaleY(1 - offset * (1 - titleScale));
        if (poi == 0) {
            btnEditFront.clearFocus();
            btnEditBack.clearFocus();
        } else if (poi == 1) {
            txtUsername.clearFocus();
            txtPassword.clearFocus();
        } else if (poi == 2) {
            editLongAddress.clearFocus();
            txtRelativeThreeContent.clearFocus();
            txtRelativeTwoContent.clearFocus();
            txtRelativeOneContent.clearFocus();
        }


        //Toolbar背景色透明度
        if (scrollY <= minHeaderHeight) {
            leftImgFirst.setVisibility(View.VISIBLE);
            if (toolbar.getVisibility() == View.GONE) {
                return;
            }
            toolbar.setVisibility(View.GONE);
        } else {
            leftImgFirst.setVisibility(View.GONE);
            if (toolbar.getVisibility() == View.VISIBLE) {
                toolbar.setBackgroundColor(Color.argb((int) (offset * 255), 227, 72, 61));
                return;
            }
            toolbar.setVisibility(View.VISIBLE);

        }

    }

    @Override
    public void showError() {

    }

    @Override
    public void complete() {
        showLoading(false);
    }

    @Override
    public void onRequestStart() {
        showLoading(true);
    }

    @Override
    public void getIdentityInfoSuccess(int poi, IdentityModel item) {

        if (poi == 0) {
//       正面
            if (TextUtils.isEmpty(item.getName()) || TextUtils.isEmpty(item.getGendor()) || TextUtils.isEmpty(item.getNation()) || TextUtils.isEmpty(item.getBirthday()) || TextUtils.isEmpty(item.getAddress()) || TextUtils.isEmpty(item.getIdno()) || TextUtils.isEmpty(item.getFront_image())) {
                ToastUtil.makeText(this, getResources().getString(R.string.not_discern_front), Toast.LENGTH_SHORT).show();
                frontIdentity = false;
                return;
            }
            take1.setVisibility(View.VISIBLE);
            frontIv.setImageBitmap(IdCardBitmap.bitmap);
            layoutIdentityTotal.setVisibility(View.VISIBLE);
            if (layoutFront.getVisibility() == View.GONE) {
                layoutFront.setVisibility(View.VISIBLE);
                measureView(0);
//                api.setAnimation(false, layoutFront);
            }
            newModel.setName(item.getName());
            newModel.setFront_image(item.getFront_image());
            newModel.setIdno(item.getIdno());
            newModel.setBirthday(item.getBirthday());
            newModel.setGendor(item.getGendor());
            newModel.setAddress(item.getAddress());
            newModel.setNation(item.getNation());
            frontIdentity = true;

            txtName.setText(item.getName());
            txtIdno.setText(item.getIdno());

//            if (isFirst) {
//                isFirst = false;
//                layoutIdcardTop.setBackgroundResource(R.drawable.bg_idcard_pin_top);
//            }

        } else if (poi == 1) {
//            反面F
            if (TextUtils.isEmpty(item.getIssue_by()) || TextUtils.isEmpty(item.getValid_start()) || TextUtils.isEmpty(item.getValid_end()) || TextUtils.isEmpty(item.getBack_image())) {
                ToastUtil.makeText(this, getResources().getString(R.string.not_discern_back), Toast.LENGTH_SHORT).show();
                backIdentity = false;
                return;
            }

            take2.setVisibility(View.VISIBLE);
            backIv.setImageBitmap(IdCardBitmap.bitmap);
            layoutIdentityTotal.setVisibility(View.VISIBLE);
            if (layoutBack.getVisibility() == View.GONE) {
                layoutBack.setVisibility(View.VISIBLE);
                measureView(0);
//                api.setAnimation(false, layoutBack);
            }
            newModel.setValid_start(item.getValid_start());
            newModel.setValid_end(item.getValid_end());
            newModel.setBack_image(item.getBack_image());
            newModel.setIssue_by(item.getIssue_by());
            backIdentity = true;

            txtAddress.setText(item.getIssue_by());
            String start = item.getValid_start();
            if (start.length() == 8) {
                start = start.substring(0, 4) + "." + start.substring(4, 6) + "." + start.substring(6, 8);
            }

            String end = item.getValid_end();
            if (end.length() == 8) {
                end = end.substring(0, 4) + "." + end.substring(4, 6) + "." + end.substring(6, 8);
            }

            txtTime.setText(start + "-" + end);


//            if (isFirst) {
//                isFirst = false;
//                layoutIdcardTop.setBackgroundResource(R.drawable.bg_idcard_pin_top);
//            }
        }
    }

    @Override
    public void getSubmitidCardSuccess(ResponseModel item) {
        ToastUtil.makeText(this, "认证成功").show();
        if (totalData.data.xuexin.is_auth.equals("0") || totalData.data.xuexin.is_auth.equals("2")) {
            setAnimationOne(layoutTakePhoto);
            setAnimationTwo(layoutChsiToal);
        } else if (totalData.data.bankcard.is_auth.equals("0") || totalData.data.bankcard.is_auth.equals("2")) {
            setAnimationOne(layoutTakePhoto);
            setAnimationTwo(layoutBankTotal);
        } else {
            api.getQuota();
        }
    }

    @Override
    public void getChsiCodeSuccess(ResponseModel model) {
        String imgStr = "";
        if (model.getMsg().contains(",")) {
            imgStr = model.getMsg().substring(model.getMsg().indexOf(',') + 1);
            codeIv.setImageBitmap(ImageUtil.stringtoBitmap(imgStr));
            codeView.setVisibility(View.VISIBLE);
            measureView(1);
        } else codeIv.setImageDrawable(null);
    }

    @Override
    public void getChsiLoginSuccess(ResponseModel item) {
        ToastUtil.makeText(this, "认证成功").show();
        if (totalData.data.bankcard.is_auth.equals("0") || totalData.data.bankcard.is_auth.equals("2")) {
            setAnimationOne(layoutChsiToal);
            setAnimationTwo(layoutBankTotal);
        } else {
            api.getQuota();
        }
    }

    @Override
    public void getChsiLoginFail(ResponseModel item) {
        ToastUtil.makeText(this, item.getMsg()).show();
//        if (checkUsername() && checkPassword())
//            api.getChsiCode(UI.toString(txtUsername), UI.toString(txtPassword));
    }

    @Override
    public void getChsiNeedCode(String code) {
        if (codeView.getVisibility() == View.VISIBLE) {
            ToastUtil.makeText(this, "图片验证码错误");
        }
        codeView.setVisibility(View.VISIBLE);
        String imgStr = "";
        if (code.contains(",")) {
            imgStr = code.substring(code.indexOf(',') + 1);
            codeIv.setImageBitmap(ImageUtil.stringtoBitmap(imgStr));
            measureView(1);
        } else codeIv.setImageDrawable(null);
//        api.getChsiCode(UI.toString(txtUsername), UI.toString(txtPassword));
    }

    @Override
    public void getBankListSuccess(BankListModel model) {
        realName = model.getReal_name();
        UserGlobal.setRealName(realName);
        if (!TextUtils.isEmpty(realName))
            name.setText("添加银行卡\n" + getResources().getString(R.string.add_bank_text1) + realName.replace(realName.substring(0, 1), "*") + getResources().getString(R.string.add_bank_text2));

        if (model.getBanks().size() <= 0) return;
        bankIdentity = true;
        bankView.setEnabled(false);
        if (!TextUtils.isEmpty(model.getBanks().get(0).getCardtype())) {
            name.setText(model.getBanks().get(0).getName() + "    " + model.getBanks().get(0).getCardtype());
        } else {
            name.setText(model.getBanks().get(0).getName());
        }
        cardno.setText(model.getBanks().get(0).getBankcard());
        if (!TextUtils.isEmpty(model.getReal_name())) realName = model.getReal_name();

        rlDefaultBankIcon.setVisibility(View.GONE);
        bankViewItem = new BankViewItem();
        int id = bankViewItem.getBankRes(model.getBanks().get(0).getName());
        flBankView.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), android.R.color.transparent));
        icon.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), bankViewItem.bankImg[id]));
        bankView.setCardBackgroundColor(ContextCompat.getColor(getApplicationContext(), bankViewItem.bankColor[id]));
    }

    @Override
    public void animationOneEnd() {
        if (poi == 0) {
            if (totalData.data.xuexin.is_auth.equals("0") || totalData.data.xuexin.is_auth.equals("2")) {
                poi++;
            } else if (totalData.data.bankcard.is_auth.equals("0") || totalData.data.bankcard.is_auth.equals("2")) {
                poi = 2;
            }
            layoutTakePhoto.setVisibility(View.GONE);
        } else if (poi == 1) {
            if (totalData.data.bankcard.is_auth.equals("0") || totalData.data.bankcard.is_auth.equals("2")) {
                poi = 2;
            }
            layoutChsiToal.setVisibility(View.GONE);
        } else if (poi == 2) {
            layoutBankTotal.setVisibility(View.GONE);
        }
    }

    @Override
    public void getRelativeAddressSuccess() {
        api.getQuota();
    }

    @Override
    public void updateAddressSuccess(AddressModel item) {
        if (isRelativeIdentity) {
            api.getQuota();
        } else {
            api.getRelativeAddress("", UI.toString(txtRelativeTwoContent), UI.toString(txtRelativeThreeContent), UI.toString(txtRelativeOneContent));
        }
    }

    @Override
    public void getQuotaSuccess(String quota) {
        if (totalData.data.sta.equals("2")) {
            finish();
        } else {
            Dialog.showDefaultDialog(this, "提示", quota, "", "确认", false, new Dialog.DialogDefaultClickListener() {
                @Override
                public void confirm() {
                    finish();
                }

                @Override
                public void cancel() {

                }
            });
        }
    }

    @Override
    public void getRelativeListSuccess(RelativeListModel item) {
        if (item.data.size() != 0) {
            isRelativeIdentity = true;
            rlRelativeSelect.setEnabled(false);
            txtRelativeTwoContent.setEnabled(false);
            txtRelativeOneContent.setEnabled(false);
            txtRelativeThreeContent.setEnabled(false);
            btnBankTongxun.setEnabled(false);
            llRelativeTwo.setEnabled(false);
            llRelativeThree.setEnabled(false);
            txtRelativeOneContent.setText(item.data.get(0).relation);
            txtRelativeTwoContent.setText(item.data.get(0).name);
            txtRelativeThreeContent.setText(item.data.get(0).mobile);
        }
    }


    /**
     * 上传身份证
     *
     * @param paramInt
     */
    private void getIdentity(int paramInt) {
        String str = "";
        if (paramInt == 0) {
//            正面
            str = ImageUtil.Bitmap2StrByBase64(IdCardBitmap.bitmap);
        } else if (paramInt == 1) {
//            反面
            str = ImageUtil.Bitmap2StrByBase64(IdCardBitmap.bitmap);
        }
        api.getIdentityInfo(paramInt, str);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100) {
            if (resultCode == -1) {
                try {
                    if (btnId == 1) {
                        if (IdCardBitmap.bitmap != null) {
//                            take1.setVisibility(View.VISIBLE);
//                            frontIv.setImageBitmap(IdCardBitmap.bitmap);
                            getIdentity(0);
                        }

                    } else if (btnId == 2) {
                        if (IdCardBitmap.bitmap != null) {
//                            take2.setVisibility(View.VISIBLE);
//                            backIv.setImageBitmap(IdCardBitmap.bitmap);
                            getIdentity(1);
                        }
                    }


                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else if (requestCode == 300) {
            if (data == null) {
                return;
            }
            //处理返回的data,获取选择的联系人信息
            Uri uri = data.getData();
            String[] contacts = api.getPhoneContacts(uri);
            if (contacts == null) {
                ToastUtil.makeText(this, "请开启读取联系人权限", Toast.LENGTH_SHORT).show();
                return;
            }
            if (TextUtils.isEmpty(contacts[1].replace(" ", ""))) {
                ToastUtil.makeText(this, "联系人电话为空或未开启读取联系人权限", Toast.LENGTH_SHORT).show();
                return;
            }
//                    去除空格，否者传上去格式有误
            txtRelativeTwoContent.setText(contacts[0].replace(" ", ""));
            txtRelativeThreeContent.setText(contacts[1].replace(" ", ""));
        } else if (requestCode == 301) {
//            if (resultCode == RESULT_OK) {
//
//            }
        }
    }


    @TargetApi(Build.VERSION_CODES.M)
    private void checkCameraPermission(final int type) {
        checkPermission(new CheckPermListener() {
            @Override
            public void superPermission() {
                if (type == 1) {
                    btnId = 1;
                    api.startCameraActivity();
                } else if (type == 2) {
                    btnId = 2;
                    api.startCameraActivity();
                }
            }

            @Override
            public void superReject() {

            }
        }, R.string.camera_storage_card_p, R.string.get_cammra, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }

    /**
     * 是否显示加载框
     *
     * @param b
     */
    private void showLoading(boolean b) {
        if (loading != null) {
            if (b)
                loading.setVisibility(View.VISIBLE);
            else
                loading.setVisibility(View.GONE);
        }
    }

    @Override
    public void onAddressSelected(Province province, City city, County county, Street street) {
        String s =
                (province == null ? "" : province.name) +
                        (city == null ? "" : city.name) +
                        (county == null ? "" : county.name) +
                        (street == null ? "" : street.name);

        if (province != null) {
            this.province = province.name;
        }
        if (city != null) {
            this.city = city.name;
        }
        if (county != null) {
            if (street != null) {
                area = county.name + street.name;
            } else {
                area = county.name;
            }
        }
        txtAreaContent.setText(s);
        bottomDialog.dismiss();
    }
}